<style>
    .menu-title{
        width: inherit !important;

    }
</style>
<form id="addIdenManageForm" lay-filter="editGroupForm" class="layui-form model-form">
    <div class="model-form-body" style="max-height: 550px;">
        <div class="layui-form-item">
            <label class="layui-form-label menu-title">已关联目录:</label>
            <div  class="layui-input-block">
                <p class="title" id="relationMenuName"></p>
            </div>
            <button type="button" id="relieve-btn" class="layui-btn layui-btn-sm layui-btn-primary">解除关联</button>
        </div>
        <div class="layui-row">
            <div class="layui-col-md6">
                <div class="layui-card">
                    <div class="layui-card-header">目录分组</div>
                    <div class="layui-card-body">
                        <ul id="setMenuGroun">

                        </ul>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-card">
                    <div class="layui-card-header">目录</div>
                    <div class="layui-card-body">
                        <ul id="menu-tree" class="ztree" ></ul>
                    </div>
                </div>
            </div>
        </div>

    </div>
    <div class="layui-form-item text-right model-form-footer">
        <button class="layui-btn layui-btn-primary layui-btn-sm" type="button" ew-event="closePageDialog">取消</button>
        <button class="layui-btn layui-btn-sm" lay-filter="setMenu" lay-submit >确定</button>
    </div>
</form>
<!--渲染目录分组-->
<script type="text/tmpl" id="template-menuGroup-tmpl">
     {{each records}}
        <li class="menu_group" style="box-sizing: border-box;padding: 0 10px;" data-id="{{$value.id}}">{{$value.name}}</li>
    {{/each}}
</script>
<script>
    layui.use(['layer', 'form', 'admin','tree','laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var admin = layui.admin;
        var upload = layui.upload;
        var laydate = layui.laydate;
        var urlData = window.mSelUser;  // 列表页面传递的数据，也可以使用top.xxx
        var userInfo = getAuthority();
        var mUser = window.mSelUser;  // 列表页面传递的数据，也可以使用top.xxx
        var Authorization;
        var IdentValueSelected = {};//分组值树选中节点
        var dirrid;//暂存目录id
        var parCode;//暂存上级code
        var par_id;//暂存上级id
        var menuDetails;//暂存选中目录信息
        var menuGroup;//暂存选中目录分组
        var groupName = '';//搜索的名称
        var diriid;
        var relationMenu={};
        //获取权限方法
        if(userInfo){
            var access_token = localStorage.getExpire("access_token");
            var token_type = localStorage.getExpire("token_type");
            Authorization = token_type+" "+access_token;
            getMenuGroup();
        }
        var setting={//树设置
            identValueSetting:{//区划树设置
                edit: {
                    enable: true,
                    showRemoveBtn: false,
                    showRenameBtn: false,
                    drag: {
                        isCopy: true,
                        isMove: false,
                        prev: false,
                        next: false,
                        inner: false
                    }
                },
                data: {
                    key: {
                        children: "sub",
                        isParent: "isParent",
                        title: "name"
                    },
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onExpand: onExpandIdentValueTree,
                    onClick: identValueOnClick
                },
                view: {
                    showIcon: true,
                    showLine: true
                }
            },
        }
        form.render('select')
        form.render('checkbox')
        // 表单提交事件
        form.on('submit(setMenu)', function (data) {
            let formData = {
                diriid:diriid,
                dirrid:dirrid,
                metid:mUser.menuData.id
            }
            axios({
                method: 'post',
                data:$.param(formData),
                url:microUrl.microObject.setMenu.addSetMenu,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 1});
                        getRelationMenu();
                    } else {
                        layer.msg(res.data.message, {icon: 2});
                        layer.closeAll('loading');
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
            return false;
        });
        //获取关联目录
        function getRelationMenu() {
            axios.get(microUrl.microObject.setMenu.searchDirMenu,{
                params:{
                    dirrid,
                    metid :mUser.menuData.id
                },
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        if(data){
                            relationMenu = data
                            $('#relationMenuName').html(data.name)
                        }else {
                            $('#relationMenuName').html('')
                        }

                    }
                })
                .catch(function (error) {
                    console.log(error)
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }
        //解除关联关系
        $('#relieve-btn').click(function () {
            if(!relationMenu.diriid){
                layer.msg('该分组暂未设置目录', {icon: 2});
                return false
            }

            layer.confirm('确定解除基层表与目录“'+relationMenu.name+'”的关系吗？', {
                skin: 'layui-layer-admin',
                shade: .1
            }, function (i) {
                layer.close(i);
                layer.load(2);
                let deleteDirMenu = {
                    diriid:relationMenu.diriid,
                    metid:mUser.menuData.id
                }
                axios({
                    method: 'delete',
                    url:microUrl.microObject.setMenu.deleteDirMenu,
                    params:deleteDirMenu,
                    headers:{
                        'Authorization':Authorization
                    }
                })
                    .then(function (res) {
                        if (res.status == 200&&res.data.message=="success") {
                            layer.closeAll('loading');
                            layer.msg("解除成功", {icon: 1});
                            relationMenu = {};
                            getRelationMenu();
                        } else {
                            layer.msg(res.data.message, {icon: 2});
                            layer.closeAll('loading');
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                            // 进行重新登陆
                            localStorage.clear();
                            top.location.href=loginPageUrl;
                        }
                    })
            });
        })
        //获取树形目录的值
        function getTreeTable(obj,callback) {
            let parcode = obj.code?obj.code:'root';
            axios({
                method: 'get',
                url:metadataUrl.menuManage.menuTree.menuTreeList+'/'+ dirrid + '/' + parcode,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        var resArr = [];
                        zhuanHuanTree(data,resArr);
                        parCode = '';
                        par_id = '';
                        menuDetails = {};
                        // IdentValueTree = resArr;
                        callback(resArr)

                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }
        //转换菜单集合数据
        function zhuanHuanTree(tdata,resData) {
            if(Array.isArray(tdata) && tdata.length>0){
                tdata.forEach(function(v,i){
                    var newValue=v.name;
                    resData[i]=v;
                    resData[i].title=newValue;
                    resData[i].icon = "";
                    resData[i].isParent = "true";
                    resData[i].sub = [];
                });
            }
        }

        //查询下方区划树的下级区划值（懒加载）
        function onExpandIdentValueTree(event, treeId, treeNode) {

            if(treeNode.sub.length>0||treeNode.hasChild=='0'){
                return false
            }
            getTreeTable(treeNode,function (resArr) {
                const treeObj = $.fn.zTree.getZTreeObj("menu-tree");
                treeNode = treeObj.addNodes(treeNode,resArr);


            });
        }
        //选中分组值
        function identValueOnClick(event, treeId, treeNode){
            menuDetails = treeNode
            parCode = treeNode.code
            par_id = treeNode.id
            IdentValueSelected = treeNode;
            diriid = treeNode.id
        }
        function getMenuGroup() {
            var req={
                current: 1,
                size: 100,
            };
            axios.get(metadataUrl.menuManage.menuGroup.menuGroupList,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        var str = template("template-menuGroup-tmpl",data);
                        document.getElementById("setMenuGroun").innerHTML = str;
                        $(".menu_group").css('cursor','pointer')
                        $("#menu-tree").empty();
                        dirrid = data.records[0].id;
                        menuGroup = data.records[0]
                        $($('.menu_group')[0]).css('background','#eeeeee').siblings().css('background','#ffffff')
                        getTreeTable(data.records[0],function (resArr) {
                            $.fn.zTree.init($("#menu-tree"), setting.identValueSetting, resArr);
                            getRelationMenu();
                        });
                        $(".menu_group").click(function () {
                            dirrid = $(this).attr("data-id")
                            $(this).css('background','#eeeeee').siblings().css('background','#ffffff')
                            relationMenu = {}
                            getTreeTable({},function (resArr) {
                                $.fn.zTree.init($("#menu-tree"), setting.identValueSetting, resArr);
                                getRelationMenu();
                            });
                        })
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

    });
</script>